import numpy as np
from common.get_hw_pre import getresult
import json


# 汉王的json预测结果转为HTML格式
def transjson2html(table_info):
    str_table = ""
    str_table += "<table>"
    current_row = -1
    head_end_row = -1
    head_end = 0
    for cell in table_info["cell"]:
        if cell['row'][0] != current_row:
            if current_row == -1:
                str_table += "<thead>"
                head_end_row = cell['row'][1]
            else:
                str_table += "</tr>"
            if cell['row'][1] > head_end_row and head_end == 0:
                str_table += "</thead>"
                str_table += "<tbody>"
                head_end = 1
            current_row = cell['row'][0]
            str_table += "<tr>"
        str_table += '<td rowspan="' + str(cell['row'][1] - cell['row'][0] + 1) + '" colspan="' + str(
            cell['col'][1] - cell['col'][0] + 1) + '">'
        if 'paragh' in cell.keys():
            for para in cell['paragh']:
                lines = para["line"]
                # all_pre_lines_chars = all_pre_lines_chars + lines
                for line in lines:
                    str_table += line["code"]
        str_table += "</td>"
    str_table += "</tr>"
    str_table += "</tbody>"
    str_table += "</table>"
    return str_table


if __name__ == '__main__':
    acc = []
    filenames = []
    anns = []
    num_label = 0
    num_chars = 0

    for line in open("table/Label.txt", "r", encoding='utf-8'):
        strs = line.split("\t")
        filename = strs[0]
        filenames.append(filename)
        anns.append(json.loads(strs[1]))
    sample_metrics = []
    all_pre_cell_infos = []
    class_labels = []
    for k in range(0, 10):
        i = 6
        # 第i个文件
        label = anns[i]
        # 文本行检测
        label_chars = []
        labe_char_boxes = []

        class_label = []
        class_pre = []
        class_pre_boxs = []
        class_label_boxs = []
        cell_label_boxs = []
        cell_rowcols = []

        tables_boxs = []
        # label
        for j in range(len(label)):
            value = label[j]["transcription"]
            if value == 'table':
                class_label.append(2)
                class_label_boxs.append(label[j]["points"])
            elif value.split("-")[0] == 'cell':
                # class_label.append(3)
                xyxy = label[j]["points"]
                # class_label_boxs.append(xyxy)
                cell_label_boxs.append(xyxy)
                strs = value.split("-")
                row_cols = [int(strs[1]), int(strs[2]), int(strs[3]), int(strs[4])]
                cell_rowcols.append(row_cols)
            else:
                label_chars.append(value)
                xyxy = label[j]["points"]
                labe_char_boxes.append(xyxy)
        tables_boxs = np.array(class_label_boxs)[class_label == np.array(2)]

        tabels_infos = []
        for table_box in tables_boxs:
            str_table = ""
            str_table += "<table>"
            current_row = -1
            head_end_row = -1
            head_end = 0
            # 哪些cell 在表格中
            label_cells_info = []
            for index_cell, cell_box in enumerate(cell_label_boxs):
                # 左上 右下  右上 左下
                if cell_box[0][0] >= table_box[0][0] and cell_box[0][1] >= table_box[0][1] \
                        and cell_box[2][0] <= table_box[2][0] and cell_box[2][1] <= table_box[2][1] \
                        and cell_box[1][0] <= table_box[1][0] and cell_box[1][1] >= table_box[1][1] \
                        and cell_box[3][0] >= table_box[3][0] and cell_box[3][1] <= table_box[3][1]:
                    if cell_rowcols[index_cell][0] != current_row:
                        if current_row == -1:
                            str_table += "<thead>"
                            head_end_row = cell_rowcols[index_cell][1]
                        else:
                            str_table += "</tr>"
                        if cell_rowcols[index_cell][1] > head_end_row and head_end == 0:
                            str_table += "</thead>"
                            str_table += "<tbody>"
                            head_end = 1
                        current_row = cell_rowcols[index_cell][0]
                        str_table += "<tr>"
                    str_table += '<td rowspan="' + str(
                        cell_rowcols[index_cell][1] - cell_rowcols[index_cell][0] + 1) + '" colspan="' + str(
                        cell_rowcols[index_cell][3] - cell_rowcols[index_cell][2] + 1) + '">'
                    chars = ""
                    # cell 里面有哪些字符串行
                    for index_char, char_box in enumerate(labe_char_boxes):
                        if char_box[0][0] >= cell_box[0][0] and char_box[0][1] >= cell_box[0][1] \
                                and char_box[2][0] <= cell_box[2][0] and char_box[2][1] <= cell_box[2][1] \
                                and char_box[1][0] <= cell_box[1][0] and char_box[1][1] >= cell_box[1][1] \
                                and char_box[3][0] >= cell_box[3][0] and char_box[3][1] <= cell_box[3][1]:
                            chars += label_chars[index_char]
                    str_table += chars
                    str_table += "</td>"
            str_table += "</tr>"
            str_table += "</tbody>"
            str_table += "</table>"
            tabels_infos.append(str_table)
        # pre:
        pre_chars = []
        pre_boxes = []
        pre_table_infos = []
        pre = getresult(filenames[i])
        if 'Table' in pre.keys():
            for class_info in pre["Table"]:
                pre_table_infos.append(transjson2html(class_info))
                coords = class_info["coords"]
                class_pre_boxs.append(coords)
                class_pre.append(2)
        from common.detect import get_per_img_statistics_tab

        metrics, table_index = get_per_img_statistics_tab(class_pre_boxs, class_label_boxs, 0.5, class_pre, class_label)

        for index_ in range(len(tabels_infos)):
            from table_rec.table_tree import TEDS

            teds = TEDS()
            dis = teds.my_evaluate(pre_table_infos[index_], tabels_infos[table_index[index_]])
            acc.append(dis)
    accmean = np.mean(np.ndarray(acc))